
package webshop.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import webshop.data.Person;

/**
 * Generates a list over all the persons in the database.
 *
 * @author even & simon.
 */
public class PersonListServlet extends AbstractSuperServlet{

    /**
     * Handle requests. Sends a html page containing the department list.
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    public void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        EntityManager em = emf.createEntityManager();
        PrintWriter out = response.getWriter();

        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>"+this.getClass().getName()+"</title></head><body>");

        out.println("<table>");
        out.println("<tr><th>ID</th><th>Name</th><th>Address</th><th>Phone</th></tr>");

        // Finds all persons.
        Query q = em.createNamedQuery("Person.selectAll");
        List<Person> persons = q.getResultList();
        // Prints out all persons.
        for (Person person : persons) {
             out.println("<tr><td>"+person.getPersonId()+"</td><td>"+
                         person.getName()+"</td><td>"+
                         person.getAddress()+"</td><td>"+
                         person.getPhone()+"</td></tr>");
        }
        out.println("</table>");
        out.println("<hr/>");
        out.println("</body>");
        out.println("</html>");


        em.close();
        out.close();
    }
}

